package com.infocollect.project.grant.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.infocollect.framework.web.domain.AjaxResult;
import com.infocollect.project.grant.domain.*;
import com.infocollect.project.grant.mapper.GrExamPointMapper;
import com.infocollect.project.grant.service.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("usergrant/")
public class SignedInterFaceController {
    private static final Logger log = LoggerFactory.getLogger(SignedInterFaceController.class);
    @Autowired
    private IGrGrantService grantServiceImpl;

    @Autowired
    private IGrExamPointService examPointServiceImpl;

    @Autowired
    private IGrSceneService GrSceneServiceImpl;

    @Autowired
    private IGrExaminerService grExaminerServiceImpl;

    @Autowired
    private IGrExaminerSceneService grExaminerSceneServiceImpl;

    @Autowired
    private GrExamPointMapper grExamPointMapper;

    @RequestMapping("/padSignIn")
    @ResponseBody
    public AjaxResult padSignIn(String grantId, String exampointId, String idCard, String address, HttpServletRequest req) {
        /**
         * 1.判断项目是否存在
         * 2.判断考点是否存在
         * 3.判断场次是否存在
         * 4。获取考官信息
         * 5.判断用户的考点和当前签到考点是否匹配
         * 6.判断是否已经签到
         *
         *
         */
        if(grantId==null || exampointId==null || idCard==null) {
            return AjaxResult.error("参数不完整");
        }
        AjaxResult result = checkGrant(Long.parseLong(grantId));
        if((Integer) result.get("code")!=200) {
            //1项目不存在
            return result;
        }
        GrGrant grant = (GrGrant)result.get("data");
        result = checkExamPoint(exampointId);
        if((Integer) result.get("code")!=200) {
            //2考点不存在
            return result;
        }
        GrExamPoint examPoint = (GrExamPoint)result.get("data");
        result = checkScene(Long.parseLong(grantId),exampointId);
        if((Integer) result.get("code")!=200) {
            //3场次不存在
            return result;
        }
        GrScene scene = (GrScene)result.get("data");
        result = checkExaminer(idCard, address);
        if((Integer) result.get("code")!=200) {
            //4考官不存在
            return result;
        }
        GrExaminer examiner = (GrExaminer)result.get("data");
        Long signExaminerId = examiner.getId();



        //判断考官所属考点与当前考点是否一致
        result = checkExaminerForPoint(Long.parseLong(grantId),examiner.getId(),exampointId);
        if((Integer) result.get("code")!=200) {
            return result;
        }
        String userExamPointName = (String)result.get("data");
        //获取考官在签到表对应的记录
        result = getExaminerScene(examiner.getId(),Long.parseLong(grantId),scene.getId(),Long.valueOf(exampointId));
        if((Integer) result.get("code")!=200) {
            return result;
        }
        GrExaminerScene grExaminerScene = (GrExaminerScene)result.get("data");

        return updGrExaminerSceneForPad(grExaminerScene,signExaminerId);
    }
    private void sendSignSms(Long examinerId,String classroom,String groupname) {
        GrExaminer grExaminer = grExaminerServiceImpl.selectGrExaminerById(examinerId);
//        String templateId = GlobalUtil.getValue("smsSignTemp");// 签到短信模版
        //classroom  评卷教室
        //groupname  证卷题组
        final LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("classroom", classroom);
        map.put("groupname", groupname);
        //先暂时不发了。
//        try {
//            MessageSenderUtil.getInstance().sendMessage(grExaminer.getPhone(), templateId, map);
//        } catch (Exception e) {
//            log.error("SEND SMS ERROR ", e);
//        }
    }
    /**
     * 检测项目是否存在
     * @param grantId
     * @return grant
     */
    public AjaxResult checkGrant(Long grantId) {
        GrGrant grGrant = new GrGrant();
        grGrant.setGrantId(grantId);
        List<GrGrant> grantsList = grantServiceImpl.selectGrGrantList(grGrant);
        if (grantsList != null && grantsList.size() > 0) {
            GrGrant resultGrant = grantsList.get(0);
            return AjaxResult.success(resultGrant);
        }
        return AjaxResult.error("项目不存在");
    }
    /**
     * 检测考点是否存在
     * @param exampointId
     * @return grant
     */
    public AjaxResult checkExamPoint(String exampointId) {
        GrExamPoint grExamPoint = null;
        if (!StringUtils.isEmpty(exampointId)) {
            grExamPoint = examPointServiceImpl.selectGrExamPointById(Long.parseLong(exampointId));
            return AjaxResult.success(grExamPoint);
        }
        return AjaxResult.error("考点不存在");
    }
    /**
     * 检测场次是否存在
     * @param grantId
     * @return grant
     */
    public AjaxResult checkScene(Long grantId,String exampointId) {
        GrScene grScene = new GrScene();
        grScene.setGrantId(grantId);
        grScene.setExampointId(Long.valueOf(exampointId));
        List<GrScene> grSceneList = GrSceneServiceImpl.selectGrSceneList(grScene);
        if (grSceneList.size()==0) {
            return AjaxResult.error("当前时间内没有可签到场次");
        }
        return AjaxResult.success(grSceneList.get(0));
    }
    /**
     * 判断考官是否存在
     * @param idCard,address
     * @return grant
     */
    public AjaxResult checkExaminer(String idCard, String address) {
        GrExaminer grExaminer = new GrExaminer();
        grExaminer.setIdcard(idCard);
        List<GrExaminer> list = grExaminerServiceImpl.selectGrExaminerList(grExaminer);
        GrExaminer examiner = new GrExaminer();
        if (list != null && list.size() > 0) {
            grExaminer = list.get(0);
            examiner.setId(grExaminer.getId());
            examiner.setName(grExaminer.getName());
            examiner.setPhone(grExaminer.getPhone());

            //如果传过来地址不为空并且库里的为空，更新人员地址
            if(StringUtils.isNotEmpty(address)&&!StringUtils.isNotEmpty(grExaminer.getAddr()))
            {
                grExaminer.setAddr(address);
                grExaminerServiceImpl.updateGrExaminer(grExaminer);
            }

            return AjaxResult.success(examiner);
        }
        return AjaxResult.error("当前人员信息不存在，请核对");
    }
    /**
     * 判断考官所属考点与当前考点是否一致
     * @param grantId
     * @return grant
     */
    public AjaxResult checkExaminerForPoint(Long grantId,Long examinerId,String exampointId) {
        GrExaminerSceneNew examinerScene = new GrExaminerSceneNew();
        examinerScene.setGrantId(grantId);
        examinerScene.setExaminerId(examinerId);
        examinerScene.setStatus(-1);
        List<GrExaminerSceneNew> list3 = grExaminerSceneServiceImpl.selectGrExaminerSceneList(examinerScene);
        if (list3 != null && list3.size() > 0) {
            boolean Flag = false;
            String userExamPointName = "";
            for (GrExaminerSceneNew grExaminerScene : list3) {
                GrExamPoint curgrExamPoint = grExamPointMapper.selectGrExamPointById(grExaminerScene.getExamPointId());// 根据考官对应的考点获取分配的考点名称
                userExamPointName += curgrExamPoint != null ? curgrExamPoint.getEpName() : "";
                userExamPointName += ",";
                if (exampointId.equals(grExaminerScene.getExamPointId().toString())) {
                    Flag = true;
                    break;
                }
            }
            if (!"".equals(userExamPointName)) {
                userExamPointName = userExamPointName.substring(0, userExamPointName.length() - 1);
            }
            if (!Flag) {
                return AjaxResult.error("考点不一致，无法签到，请确认");
            }else{
                return AjaxResult.success(userExamPointName);
            }
        }
        return AjaxResult.error("人员所对应考点不存在，无法签到，请确认");
    }
    /**
     * 判断考官是否已签到，并返回签到记录。
     * @param grantId
     * @return grant
     */
    public AjaxResult getExaminerScene(Long examinerId,Long grantId,Long sceneId,Long examPointId) {
        GrExaminerSceneNew examinerScene = new GrExaminerSceneNew();
        examinerScene.setGrantId(grantId);
        examinerScene.setExamPointId(examPointId);
        examinerScene.setSceneId(sceneId);
        examinerScene.setExaminerId(examinerId);
        examinerScene.setStatus(-1);
        List<GrExaminerSceneNew> list2 = grExaminerSceneServiceImpl.selectGrExaminerSceneList(examinerScene);
        GrExaminerSceneNew grExaminerScene = null;
        if (list2 == null || list2.size() == 0) {
            return AjaxResult.error("该人员不在签到列表!");
        } else {
            grExaminerScene = list2.get(0);
            if(grExaminerScene.getSignRemark()!=null) {
                grExaminerScene.setRemark(grExaminerScene.getSignRemark().replaceAll(",", "，"));
            }
            return AjaxResult.success(grExaminerSceneServiceImpl.selectGrExaminerSceneById(grExaminerScene.getId()));
        }
    }
    /**
     * 签到数据添加
     * @param record
     * @return
     */
    @RequestMapping("/updGrExaminerSceneForPad")
    @ResponseBody
    public AjaxResult updGrExaminerSceneForPad(GrExaminerScene record,Long signExaminerId) {
        if (record.getExaminerId() == null || record.getExampointId() == null || record.getGrantId() == null
                || record.getSceneId() == null) {
            return AjaxResult.error("签到参数异常，请重新操作");
        }
        /**
         * 1.判断是否签到
         *
         */
        GrExaminerSceneNew examinerSceneNew = new GrExaminerSceneNew();
        examinerSceneNew.setGrantId(record.getGrantId());
        examinerSceneNew.setExamPointId(record.getExampointId());
        examinerSceneNew.setSceneId(record.getSceneId());
        examinerSceneNew.setExaminerId(record.getExaminerId());
        examinerSceneNew.setStatus(-1);
        List<GrExaminerSceneNew> list = grExaminerSceneServiceImpl.selectGrExaminerSceneList(examinerSceneNew);
        GrExaminerSceneNew grExaminerSceneNew = null;
        if (list == null || list.size() == 0) {
            return AjaxResult.error("您不在本次考场中，无法签到");
        }
        grExaminerSceneNew = list.get(0);
        GrExaminerScene GrExaminerScene =grExaminerSceneServiceImpl.selectGrExaminerSceneById(grExaminerSceneNew.getId());

        if (GrExaminerScene.getSceneStatus() == 1 || GrExaminerScene.getSceneStatus() == 2) {
            AjaxResult result = new AjaxResult(200,"您已签到");
            grExaminerSceneNew = grExaminerSceneServiceImpl.selectSignedNewForId(GrExaminerScene.getId());
            if(grExaminerSceneNew.getSignRemark()!=null) {
                grExaminerSceneNew.setRemark(GrExaminerScene.getSignRemark().replaceAll(",", "，"));
            }
            sendSignSms(signExaminerId,GrExaminerScene.getRoomAddr(),GrExaminerScene.getRemark());
            result.put("data",grExaminerSceneNew);
            return result;
            //return ResultUtil.error("您已签到");
        }
        GrScene secene = GrSceneServiceImpl.selectGrSceneById(record.getSceneId());
        Date now = new Date();
        // 当前时间在开始到结束之间，属于正常
        if (!now.before(secene.getSceneStartTime()) && now.before(secene.getSceneEndTime())) {
            GrExaminerScene.setSceneStatus(1);
        } else if (secene.getSignEndTime() == null) {
            // 截止时间为空时，说明不存在迟到
            GrExaminerScene.setSceneStatus(1);
        } else if (secene.getSignEndTime() != null && !now.before(secene.getSceneEndTime())
                && now.before(secene.getSignEndTime())) {
            // 当前时间在结束到截止之间，属于迟到
            GrExaminerScene.setSceneStatus(2);
        } else {
            // 不允许签到
            return AjaxResult.error("当前时间，不允许签到");
        }
        GrExaminerScene.setTime(now);
        //GrExaminerScene.setSignExaminerId(record.getExaminerId());
        GrExaminerScene.setSignExaminerId(signExaminerId);
        Integer id = grExaminerSceneServiceImpl.updateGrExaminerScene(GrExaminerScene);
        if (id != null) {
            GrExaminerSceneNew examinerSceneNewResult = grExaminerSceneServiceImpl.selectSignedNewForId(GrExaminerScene.getId());
            if(examinerSceneNewResult.getSignRemark()!=null) {
                examinerSceneNewResult.setRemark(GrExaminerScene.getSignRemark().replaceAll(",", "，"));
            }
            AjaxResult result = new AjaxResult(0,"操作成功");
            result.put("data",examinerSceneNewResult);
            return result;
        } else {
            return AjaxResult.error("操作失败，请重新操作");
        }
    }
}
